// src/pages/hospital/hospitalSet/index.tsx
import React, { useState, useEffect, Key, useRef } from "react";
import { Card, Form, Input, Button, Table, Tooltip, message, Modal, Upload } from "antd";
import { SearchOutlined, EditOutlined, DeleteOutlined, PlusOutlined, LoadingOutlined } from "@ant-design/icons";

import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { useNavigate } from "react-router-dom";

import { useTranslation } from "react-i18next";

import { reqAddOrUpdateTradeMark, reqDeleteTradeMark, reqGetTradeMark } from "@api/user/index";

import "./index.less";

function Trademark() {
    const { t } = useTranslation(["hospitalSet"]);
    // loading
    const [loading, setLoading] = useState(false);
    // 定义医院列表数据和类型
    const [trademarkList, settrademarkList] = useState([]);
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(5);
    const [total, setTotal] = useState(0);
    const [form] = Form.useForm();

    // 封装公共请求函数
    const getTrademark = async (page: number = 1, limit: number) => {
        // 发送请求开启loading
        setLoading(true);
        // 读取表单数据

        // 发送请求携带上另外的参数
        const res = await reqGetTradeMark(page, limit);
        // 更新页码
        setCurrent(page);
        setPageSize(limit);
        // 更新总数
        setTotal(res.total);
        // 更新数据
        settrademarkList(res.records);
        // 请求完成结束loading
        setLoading(false);
    };

    // 一上来发送请求
    useEffect(() => {
        getTrademark(current, pageSize);
        // 注意：依赖数组中不能有current, pageSize
        // 因为会导致请求发送两次
    }, []);

    // 
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        // console.log(img)
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);

    };

    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };



    const handleChange = (info: UploadChangeParam<UploadFile>) => {

        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, url => {
                setImageUrl(info.file.response.data);
                // console.log(info)
            });
        }
    };

    const uploadButton = (
        <div>
            {<PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    // 双向绑定编辑添加modal数据
    const [imageUrl, setImageUrl] = useState('');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [trademarkId, setTrademarkId] = useState('');
    const [trademarkName, setTrademarkName] = useState('');
    const showModal = () => {
        setTrademarkId('');
        setTrademarkName('');
        setImageUrl('');
        setIsModalOpen(true);
    };

    const handleOk = async () => {
        const form = TrademarkFormRef.current
        form.validateFields().then(async (values: any) => {
            await reqAddOrUpdateTradeMark({ id: trademarkId, tmName: trademarkName, logoUrl: imageUrl })
            if (trademarkId) {
                message.success(`修改${trademarkName}成功`);
                getTrademark(current, pageSize)
            } else {
                message.success(`添加${trademarkName}成功`);
                getTrademark(1, 5)
            }
            setIsModalOpen(false);
        }).catch((errInfo: any) => {

        })
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 列
    const columns = [
        {
            // 标题
            title: '序号',
            width: 80,
            align: "center" as "center",
            // 渲染什么数据
            // dataIndex写啥？看接口文档返回数据的格式，数据返回叫啥就写啥
            // 接口文档没有的就自己定义，保证唯一即可
            // dataIndex: "index",
            render: (_x: any, _y: any, index: number) => {
                return index + 1;
            },
        },
        {
            title: '品牌名称',
            dataIndex: "tmName",
            width: 505,
        },
        {
            title: '品牌Logo',
            dataIndex: "logoUrl",
            width: 505,
            render: (logo: string) => (
                // base64图片技术
                // 找到一张base64格式图片，观察我们数据缺少了哪部分。加上去即可
                <img
                    className="trademark-img"
                    src={logo}
                    alt="logo"
                />
            ),
        },
        {
            title: '操作',
            align: "center" as "center",
            // 固定在右侧
            // fixed: 'right', // 报错，会自动将类型推论为string
            //fixed: "right" as "right", // 将类型断言为 'right' 字符串字面量类型就好
            width: 505,
            // 写了dataIndex就只能得到某个数据
            // 不写dataIndex，render方法就能接收到整行数据
            // 类型为单个数据
            render: (row: any) => {

                return (
                    <>

                        <Button type="primary" onClick={() => {
                            setIsModalOpen(true);
                            setTrademarkId(row.id);
                            setTrademarkName(row.tmName)
                            setImageUrl(row.logoUrl);
                        }} icon={<EditOutlined />}>
                        </Button>
                        <Button className="hospital-btn" type="primary" danger icon={<DeleteOutlined />} onClick={removeTrademark(row.id)} />

                    </>
                );
            },
        },
    ];

    // 删除品牌
    const removeTrademark = (id: number) => {
        return async () => {
            await reqDeleteTradeMark(id);
            message.success("删除成功");
            getTrademark(current, pageSize);
        };
    };

    // 功能代码尽量放一起

    const TrademarkFormRef = useRef<any>();

    return (
        <Card>
            <Button type="primary" onClick={showModal} icon={<PlusOutlined />}>添加
            </Button>
            <Modal title={trademarkId ? '修改品牌' : '添加品牌'} visible={isModalOpen} footer={[]} onCancel={() => setIsModalOpen(false)} destroyOnClose={true}>
                <Form ref={TrademarkFormRef} onFinish={handleOk}>
                    <Form.Item label="品牌名称" name={'name'} valuePropName="trademarkname" initialValue={trademarkName} rules={[{ required: true }, {
                        validator: (_, value) => {
                            if (value && trademarkName.length < 1) {
                                return Promise.reject('品牌名称不能为空')
                            } else if (value && (trademarkName.length < 2 || trademarkName.length > 10)) {
                                return Promise.reject('品牌名称必须是2-10位')
                            } else {
                                return Promise.resolve()
                            }
                        }
                    }]}>
                        <Input value={trademarkName} onChange={e => {
                            setTrademarkName(e.target.value);
                        }} placeholder="请输入品牌名称" />
                    </Form.Item>
                    <Form.Item label="品牌logo" name={'imageUrl'} initialValue={imageUrl} valuePropName="imageUrl"
                        rules={[
                            { required: true },
                            {
                                validator: (_, value) => {
                                    if (value && imageUrl) {
                                        return Promise.resolve()
                                    } else {
                                        return Promise.reject()
                                    }

                                }
                            }]}
                    >
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item style={{ float: 'right' }}>
                        <Button htmlType="button" onClick={handleCancel} >
                            取消
                        </Button>
                        <Button type="primary" htmlType="submit" style={{ marginLeft: 20 }}>
                            确认
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Table
                columns={columns}
                dataSource={trademarkList}
                bordered
                // scroll={{ x: 1500 }}
                rowKey="id"
                pagination={{
                    current,
                    pageSize,
                    total,
                    showQuickJumper: true,
                    pageSizeOptions: [5, 20, 50, 100, 1000, 30000],
                    showSizeChanger: true,
                    showTotal: (total) => `总共： ${total} 条`,
                    onChange: getTrademark,
                    onShowSizeChange: getTrademark,
                }}
                loading={loading}

            />
        </Card >
    );
}

export default Trademark;
